from django.http import JsonResponse
from django.db import connection
import json
from rest_framework.decorators import api_view
from django.db.models.aggregates import Sum
from zoneapi.models import ZoneInfo
from buildapi.models import BuildingInfo
# Create your views here.


@api_view(['POST'])
def dispatcher(request):  

    # try:
    if request.user.is_authenticated:   # 验证Token是否正确
        if request.user.is_active:
            if request.method == 'GET':
                request.params = request.GET

            # POST/PUT/DELETE 请求 参数 从 request 对象的 body 属性中获取
            elif request.method in ['POST','PUT','DELETE']:
                # 根据接口，POST/PUT/DELETE 请求的消息体都是 json格式
                request.params = json.loads(request.body)


            # 根据不同的action分派给不同的函数进行处理
            action = request.params['action']
            if action == 'list':
                return ZoneInfo_list(request)
            elif action == 'add':
                return ZoneInfo_add(request)
            elif action == 're':  
                return ZoneInfo_re(request)
            elif action == 'del':
                return ZoneInfo_del(request)
            elif action == 'like':
                return ZoneInfo_like(request)
            elif action == 'about':
                return ZoneInfo_about(request)
            elif action == 'open':
                return ZoneInfo_open(request)

            else:
                return JsonResponse({'ret': 1, 'msg': '不支持该类型http请求'})
    else:
        return JsonResponse({'ret': 2, "msg": "token验证失败"})


def ZoneInfo_open(request):
    data = json.loads(request.body)  
    zone_openid = data['zone_openid']
    try:
        index = ZoneInfo.objects.filter(zone_openid=zone_openid).values('zone_id','zone_name')
        return JsonResponse({'ret':0,'data':list(index)})
    except ZoneInfo.DoesNotExist as e:
        return JsonResponse({
                'ret': 1,
                'msg': "列表获取失败，发生异常:{}".format(e)
            })


def ZoneInfo_about(request):
    data = json.loads(request.body)  
    zone_id = data['zone_id']
    try:
        zre = ZoneInfo.objects.get(zone_id=zone_id)

        zone_house = BuildingInfo.objects.filter(building_about_id=zre.zone_id).aggregate(Sum('building_price'))
        zone_electric = BuildingInfo.objects.filter(building_about_id=zre.zone_id).aggregate(Sum('building_electric'))
        zone_water = BuildingInfo.objects.filter(building_about_id=zre.zone_id).aggregate(Sum('building_water'))
        zone_count = BuildingInfo.objects.filter(building_about_id=zre.zone_id).aggregate(Sum('building_count'))
        zone_idle_count = BuildingInfo.objects.filter(building_about_id=zre.zone_id).aggregate(Sum('building_idle_count'))
        
        zre.zone_electric = zone_electric['building_electric__sum']
        zre.zone_water = zone_water['building_water__sum']
        zre.zone_house = zone_house['building_price__sum']
        zre.zone_count = zone_count['building_count__sum']
        zre.zone_idle_count = zone_idle_count['building_idle_count__sum']
        zre.save()

        index = ZoneInfo.objects.filter(zone_id=zre.zone_id).values('zone_electric','zone_water','zone_house','zone_count',
        'zone_last_electric','zone_last_water','zone_last_house','zone_idle_count')
        return JsonResponse({'ret':0,'data':list(index)})

    except ZoneInfo.DoesNotExist as e:
        return JsonResponse({
                'ret': 1,
                'msg': "列表获取失败，发生异常:{}".format(e)
            })


def ZoneInfo_list(request):
    data = json.loads(request.body)
    openid = data['openid']
    page_max = int(data['page_max'])
    page = int(data['page'])
    try:
        index = ZoneInfo.objects.filter(zone_openid=openid).values('zone_id','zone_name','zone_address','zone_admin','zone_admin_email',
        'zone_admin_phone').order_by('zone_id')[page_max*page-page_max:page_max*page]
        count = ZoneInfo.objects.filter(zone_openid=openid).count()
        return JsonResponse({'ret':0,'data':list(index),'count':count})
    except ZoneInfo.DoesNotExist as e:
        return JsonResponse({
                'ret': 1,
                'msg': "列表获取失败，发生异常:{}".format(e)
            })


def ZoneInfo_add(request):
    data = json.loads(request.body)  
    try:
        zone_name = data['zone_name']
        zone_address = data['zone_address']
        zone_admin = data['zone_admin']
        zone_admin_phone = data['zone_admin_phone']
        zone_admin_email = data['zone_admin_email']
        zone_openid = data['zone_openid']

        if ZoneInfo.objects.filter(zone_name=zone_name,zone_openid =zone_openid).exists():
            return JsonResponse({'ret':2 , 'msg':"该小区名称{} 已经存在".format(zone_name)})
        else:
            ZoneInfo.objects.create(
            zone_electric = 0,
            zone_water = 0,
            zone_house = 0,
            zone_name = zone_name,
            zone_openid = zone_openid,
            zone_admin_phone = zone_admin_phone,
            zone_admin_email = zone_admin_email,
            zone_address = zone_address,
            zone_admin = zone_admin)
            return JsonResponse({'ret':0})

    except ZoneInfo.DoesNotExist as e:
        return JsonResponse({
                'ret': 1,
                'msg': "信息添加失败，发生异常:{}".format(e)
            })


def ZoneInfo_re(request):
    data = json.loads(request.body)  
    cursor = connection.cursor()
    try:
        key = list(data['key'])
        value = list(data['value'])
        zone_id = data['zone_id']

        # if ZoneInfo.objects.filter(zone_name=zone_name).exists()
        if len(key) > 0 :
            for i in range(len(key)):
                cursor.execute(" UPDATE zone_info SET {} = '{}' WHERE zone_id = '{}' ".format(key[i],value[i],zone_id))

        return JsonResponse({'ret':0})
    except ZoneInfo.DoesNotExist as e:
        return JsonResponse({
                'ret': 1,
                'msg': "信息修改失败，发生异常:{}".format(e)
            })

def ZoneInfo_del(request):
    data = json.loads(request.body)  
    try:
        zone_id = list(data['zone_id'])

        if len(zone_id) > 0 :
            for i in range(len(zone_id)):
                if BuildingInfo.objects.filter(building_about_id=zone_id[i]).exists():
                    return JsonResponse({
                    'ret': 2,
                    'msg': "请先删除或更改：{} 已关联的楼栋".format(zone_id[i])
                    })
                index = ZoneInfo.objects.get(zone_id=zone_id[i])
                index.delete()
    except Exception as e:
        print(e)
        return JsonResponse({
            'ret': 1,
            'msg': "信息删除失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0})

def ZoneInfo_like(request):
    data = json.loads(request.body)
    try:
        openid = data['openid']
        zone_name = data['zone_name']
        index = ZoneInfo.objects.filter(zone_name__icontains=zone_name,zone_openid=openid).values('zone_id','zone_name','zone_address',
        'zone_admin','zone_admin_email','zone_admin_phone')
    except ZoneInfo.DoesNotExist as e:
        return JsonResponse({
            'ret': 1,
            'msg': "模糊查询失败，发生异常：{}".format(e)
        })
    return JsonResponse({'ret':0,'data':list(index)})